package com.zbhk.qc.service.impl;

import com.zbhk.qc.configuration.MyException;
import com.zbhk.qc.configuration.security.SecurityConfiguration;
import com.zbhk.qc.dto.*;
import com.zbhk.qc.entity.VdUser;
import com.zbhk.qc.entity.VdUserOffline;
import com.zbhk.qc.mapper.VdUserMapper;
import com.zbhk.qc.mapper.VdUserOfflineMapper;
import com.zbhk.qc.service.UserServer;
import com.zbhk.qc.util.ConstantUtil;
import com.zbhk.qc.util.MD5Util;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhulenan on 2020/7/22 11:14
 */
@Lazy(false)
@Service("userServerImpl")
public class UserServerImpl implements UserServer {

    @Autowired
    private VdUserMapper vdUserMapper;

    @Autowired
    private VdUserOfflineMapper vdUserOfflineMapper;

    @Autowired
    private UserServer userServer;


    @Override
    public BaseResponseEntity<LoginOutput> start(LoginInput loginInput,HttpServletRequest request) {

        BaseResponseEntity<LoginOutput> responseEntity = new BaseResponseEntity();
        LoginOutput loginOutput = new LoginOutput();

        Map<String,Object> map = new HashMap<>();
        map.put("phone",loginInput.getAccount());
        List<VdUser> vdUserList = vdUserMapper.selectByMap(map);
        VdUser vdUser = new VdUser();
        if(null == vdUserList || vdUserList.size() == 0){
           /* responseEntity.setSuccess(false);
            responseEntity.setErrorMessage("账户不存在！");
            String accessToken = "";
            loginOutput.setJwt(accessToken);
            responseEntity.setData(loginOutput);
            return responseEntity;*/
            //自动注册
            UserAddVO userAddVO = new UserAddVO();
            userAddVO.setPhone(loginInput.getAccount());
            userAddVO.setName("用户"+loginInput.getAccount());
            try {
                userServer.addUser(userAddVO);
            }catch (Exception e){

            }
            vdUserList = vdUserMapper.selectByMap(map);
        }
        vdUser = vdUserList.get(0);
        if(MD5Util.createMD5(loginInput.getPassword()).equals(vdUser.getPassword())){
            responseEntity.setSuccess(true);
            String accessToken = Jwts.builder()
                    .setSubject(String.valueOf(vdUser.getPhone()))
                    .setExpiration(new Date(System.currentTimeMillis() + SecurityConfiguration.ACCESS_EXPIRATION_TIME))
                    .signWith(SignatureAlgorithm.HS512, SecurityConfiguration.ACCESS_SECRET.getBytes())
                    .compact();
            loginOutput.setJwt(accessToken);
            loginOutput.setVdUser(vdUser);
            responseEntity.setData(loginOutput);
            return responseEntity;
        }else {
            responseEntity.setSuccess(false);
            responseEntity.setErrorMessage("密码错误！");
            String accessToken = "";
            loginOutput.setJwt(accessToken);
            responseEntity.setData(loginOutput);
            return responseEntity;
        }
    }

    @Override
    public VdUser addUser(UserAddVO userAddVO) throws Exception{

        if(StringUtils.isEmpty(userAddVO.getPhone()) && StringUtils.isEmpty(userAddVO.getWecharCode())){
            throw new MyException("微信号和手机号不能同时为空！");
        }
        //手机号去重
        List<VdUser> list =  vdUserMapper.getListByPW(userAddVO.getPhone(),userAddVO.getWecharCode());
        if(list.size()>0 ){
            throw new MyException("此微信号或手机号已存在！");
        }
        VdUser vdUser = new VdUser();
        BeanUtils.copyProperties(userAddVO,vdUser);
        vdUser.setPassword(MD5Util.createMD5(ConstantUtil.DEFAULT_PASSWORD));
        vdUserMapper.insert(vdUser);
        //处理上下级关系表
        VdUserOffline vdUserOffline = new VdUserOffline();
        vdUserOffline.setUserId(userAddVO.getPUserId());
        vdUserOffline.setSUserId(vdUser.getId());
        vdUserOfflineMapper.insert(vdUserOffline);
        return vdUser;
    }

    @Override
    public Map<String, Object> getUpDownDetail(Long id) {
        Map<String,Object> map = new HashMap<>();
        VdUser vdUser = vdUserMapper.selectById(id);
        map.put("user",vdUser);
        if(null != vdUser){
          List<UpDowmVO> list =   vdUserOfflineMapper.selectDetail(id);
          map.put("downUserList",list);
        }
        if(null != vdUser){
            if(null != vdUser.getPUserId()){
                VdUser user =   vdUserMapper.selectById(vdUser.getPUserId());
                map.put("upUser",user);
            }else {
                map.put("upUser","");
            }
        }
        return map;
    }


}

  